//
//  MainViewController.m
//  AntsExpress
//
//  Created by slccper on 16/1/1.
//  Copyright © 2016年 slccper. All rights reserved.
//
#define Cell1Width (ScreenWidth-3)/4

#import "MainViewController.h"
#import "BannerScrollView.h"
#import "MainViewCell.h"
#import "clsMain.h"
#import "AppDelegate.h"
#import "clsBannerSetting.h"
#import "RNBlurModalView.h"
#import "clsOtherFun.h"
#import "clsAntsService.h"
#import "LoginViewController.h"
#import "RegisteredController.h"
#import "AccountViewController.h"
#import "CalculationController.h"
#import "NewsController.h"
#import "WechatViewController.h"
#import "TabbaoController.h"
#import "DifficultController.h"
#import "SendViewController.h"
#import "ProblemViewController.h"
#import "ChargeViewController.h"
#import "clsFileFun.h"
#import "clsCategory.h"
#import "UIAlertView+Blocks.h"
#import "clsCheck.h"
#import "PullTableView.h"
#import "RecordsViewController.h"
#import "Charge1ViewController.h"
#import "WebViewController.h"
@interface MainViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource,clsAntsServiceDelegate,UINavigationControllerDelegate,PullTableViewDelegate>
{
    NSMutableArray *_list;
    RNBlurModalView *_modal;
    NSMutableArray *_tableList;
    clsAntsService *ants;
    UIImageView *member;
    UILabel *mname;
    UILabel *mid;
    UILabel *membermoney;
    UILabel *memberno;
    UIButton *new;
}
@property (nonatomic, retain) BannerScrollView *bannerView;
@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) PullTableView *collectionView;
//@property (nonatomic, retain) UITableView *tableView;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //登录转台变化通知更改信息方法
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showNavigation) name:@"LoginChange" object:nil];
    
    UIView *HeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 2*Cell1Width*85/94+128.0f*ScreenWidth/320.0f+40+30)];
    float top=0;
    CGRect rect = self.view.frame;
    rect.origin.x = 0.0f;
    rect.origin.y = top;
    new = [UIButton buttonWithType:UIButtonTypeCustom];
    [new setFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    [new setTitle:[clsOtherFun getNewTitle] forState:UIControlStateNormal];
    [new setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    new.backgroundColor = [UIColor orangeColor];
    [new.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [new addTarget:self action:@selector(NewAction:) forControlEvents:UIControlEventTouchUpInside];
    [HeaderView addSubview:new];
    float height = 2*Cell1Width*85/94+1;
    rect.size.height = height;
    rect.origin.y+=40;
    top +=Cell1Width*85/94+Cell1Width*85/94+40+5;
    _list = [clsMain MainList];
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing=1;
//    flowLayout.itemSize = CGSizeMake(96, 100);
    self.collection = [[UICollectionView alloc]initWithFrame:rect collectionViewLayout:flowLayout];
    self.collection.delegate=self;
    self.collection.dataSource=self;
    self.collection.backgroundColor=[UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:0.1];
    self.collection.showsVerticalScrollIndicator=NO;
    self.collection.scrollsToTop=NO;
//    [self.collection registerClass:[MainViewCell class] forCellWithReuseIdentifier:@"MainViewCell"];
    [self.collection registerNib:[UINib nibWithNibName:@"MainViewCell" bundle:nil] forCellWithReuseIdentifier:@"MainViewCell"];
    //    [self.collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FooterView"];
    [HeaderView addSubview:self.collection];
//    _bannerList = [NSMutableArray array];
//    for (int i=0; i<5; i++) {
//        clsBannerSetting *banner = [[clsBannerSetting alloc]init];
////        [banner setPhoto:@"1"];
////        [banner setBannerSettingID:@"1"];
//        [_bannerList addObject:banner];
//    }
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, top, ScreenWidth, 40)];
    view.backgroundColor = [UIColor redColor];
    memberno = [[UILabel alloc]initWithFrame:CGRectMake(10, 9, 200, 22)];
    memberno.textAlignment= NSTextAlignmentLeft;
    memberno.font = [UIFont systemFontOfSize:17];
    memberno.textColor=[UIColor whiteColor];
    memberno.tag = 10000;
    [view addSubview:memberno];
    if ([[clsOtherFun getMemberId] integerValue]!=0) {
        memberno.text = [NSString stringWithFormat:@"會員編號：%ld",(long)[[clsOtherFun getMemberId] integerValue]+600000];
    }else{
        memberno.text = [NSString stringWithFormat:@"會員編號："];
    }
    membermoney = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-160, 9, 150, 22)];
    membermoney.textAlignment= NSTextAlignmentRight;
    membermoney.font = [UIFont systemFontOfSize:17];
    membermoney.textColor=[UIColor whiteColor];
    membermoney.text = [NSString stringWithFormat:@"M幣：%.2f",[[clsOtherFun getVIPMoney] floatValue]];
    membermoney.tag = 10086;
    [view addSubview:membermoney];
    [HeaderView addSubview:view];
    top +=40;
    if ([_bannerList count] > 0) {
        CGRect rect = self.view.frame;
        rect.origin.x = 0.0f;
        rect.origin.y = top;
        rect.size.height = 300*ScreenWidth/600;
        rect.size.width = ScreenWidth;
        self.bannerView = [[BannerScrollView alloc] initWithFrame:rect];
        self.bannerView.list = _bannerList;
        self.bannerView.parentVC = self;
        [self.bannerView loadData];
        [HeaderView addSubview:self.bannerView];
        top += 300*ScreenWidth/600;
    }
    UIView *allLabel = [[UIView alloc]initWithFrame:CGRectMake(0, top, ScreenWidth, 30)];
    allLabel.backgroundColor = [UIColor whiteColor];
    [allLabel addSubview:[self CreatByText:@"運單號" :0]];
    [allLabel addSubview:[self CreatByText:@"狀態" :1]];
    [allLabel addSubview:[self CreatByText:@"收件日" :2]];
    [allLabel addSubview:[self CreatByText:@"到期日" :3]];
    [allLabel addSubview:[self CreatByText:@"費用" :4]];
    [clsOtherFun addAllLayoutConstraints:allLabel];
    [HeaderView addSubview:allLabel];
    [HeaderView setFrame:CGRectMake(0, 0, ScreenWidth, top+40)];
    self.collectionView = [[PullTableView alloc] initWithFrame:rect];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.collectionView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.collectionView.pullDelegate = self;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor lightGrayColor];
    self.collectionView.pullBackgroundColor = [UIColor lightGrayColor];
    self.collectionView.pullArrowImage = [UIImage imageNamed:@"blackArrow"];
//    [self.view addSubview:self.collectionView];
    
//    [self.tableView setFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-40)];
    self.tableView=self.collectionView;
    self.tableView.tableHeaderView = HeaderView;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self showNavigation];
    _tableList = [NSMutableArray array];
    ants = [[clsAntsService alloc]init];
    ants.delegate=self;
    self.navigationController.delegate=self;
    [self performSelector:@selector(mainpush) withObject:nil afterDelay:3.0];
    // Do any additional setup after loading the view.
}
-(void)mainpush
{
    if ([[clsCheck sharedManager]objectForKey:@"new"]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"NewPush" object:nil];
    }
    
}
- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated
{
    BOOL isSelf = [viewController isKindOfClass:[MainViewController class]];
    navigationController.interactivePopGestureRecognizer.enabled = !isSelf;
}

-(void)showNavigation
{
    
    NSString *memberid = [clsOtherFun getMemberId];
    if ([memberid integerValue]) {
        UIButton *logout = [[UIButton alloc]initWithFrame:CGRectMake(0,0,70,30)];
        [logout setTitle:@"登出" forState:UIControlStateNormal];
        [logout setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [logout addTarget:self action:@selector(logout:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftbar = [[UIBarButtonItem alloc]initWithCustomView:logout];
        [self.navigationItem setRightBarButtonItem:leftbar];
        [self getUserData];
    }else{
        UIButton *logout = [[UIButton alloc]initWithFrame:CGRectMake(0,0,75,30)];
        [logout setTitle:@"注冊登入" forState:UIControlStateNormal];
        [logout setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [logout addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftbar = [[UIBarButtonItem alloc]initWithCustomView:logout];
        [self.navigationItem setRightBarButtonItem:leftbar];
        [_tableList removeAllObjects];
        [self loadDataSource];
        [self.tableView reloadData];
        [clsOtherFun setName:nil];
        [self getHotNew];
    }
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0,150, 44)];
    NSString *photo = [clsOtherFun getMemberPhoto];
    photo = [photo stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSData *photodata = [[NSData alloc]initWithBase64EncodedString:photo options:NSDataBase64DecodingIgnoreUnknownCharacters];
    member = [[UIImageView alloc] initWithFrame:CGRectMake(0, 3, 35, 35)];
    member.contentMode = UIViewContentModeScaleAspectFit;
    UIImage *image =[UIImage imageWithData:photodata];
    if (image) {
        member.image = image;
    }else{
        member.image = [UIImage imageNamed:@"default_profile_pic.png"];;
    }
    mname = [[UILabel alloc]initWithFrame:CGRectMake(45, 0, 200, 44)];
    [mname setText:[NSString stringWithFormat:@"歡迎您，%@",[clsOtherFun getMemberName]]];
    mname.font = [UIFont systemFontOfSize:18];
    mname.textColor = [UIColor whiteColor];
    [view addSubview:mname];
    if ([[clsOtherFun getMemberId] integerValue]!=0) {
        memberno.text = [NSString stringWithFormat:@"會員編號：%ld",(long)[[clsOtherFun getMemberId] integerValue]+600000];
    }else{
        memberno.text = [NSString stringWithFormat:@"會員編號："];
    }
    membermoney.text = [NSString stringWithFormat:@"M幣：%.2f",[[clsOtherFun getVIPMoney] floatValue]];
//    mid = [[UILabel alloc]initWithFrame:CGRectMake(45, 21, 100, 21)];
//    if ([memberid integerValue]!=0) {
//        [mid setText:[NSString stringWithFormat:@"ID:%ld",[memberid integerValue]+600000]];
//    }else{
//        [mid setText:[NSString stringWithFormat:@"ID:"]];
//    }
//    
//    mid.font = [UIFont systemFontOfSize:12];
//    mid.textColor = [UIColor whiteColor];
//    [view addSubview:mid];
    [view addSubview:member];
    UIBarButtonItem *leftbar = [[UIBarButtonItem alloc]initWithCustomView:view];
    [self.navigationItem setLeftBarButtonItem:leftbar];
}

-(void)getUserData
{
    if ([clsOtherFun CheckNetworkStatus:YES]) {
        if (ants) {
            [ants cancel];
            ants.delegate = nil;
            ants = nil;
        }
        [clsOtherFun showLoadingView:@"正在獲取數據"];
        ants = [[clsAntsService alloc]init];
        ants.delegate=self;
        [ants MyExpressQuery];
    }else{
        [self performSelector:@selector(loadDataSource) withObject:nil afterDelay:0.1];
    }
    
}
- (void)loadDataSource
{
    self.collectionView.pullTableIsRefreshing = NO;
    self.collectionView.pullTableIsLoadingMore=NO;
    self.collectionView.pullLastRefreshDate = [NSDate date];
    [self.collectionView reloadData];
}
-(void)getAntsDataFail:(NSInteger)type
{
    [clsOtherFun hideLoadingView];
    if(type == Ants_MyExpressQuery){
        [self loadDataSource];
    }
}
#warning 网络回调
//callback network 网络回调
-(void)getAntsDataSuccess:(NSInteger)type :(NSMutableDictionary *)pDictionary
{
    [clsOtherFun hideLoadingView];
    // distinguish by type 根据type区分方法进行处理
    if (type ==Ants_GetHotNews) {
        NSDictionary *dic = [pDictionary objectForKey:@"data"];
        NSArray *arr =[dic objectForKey:@"data"];
        NSDictionary *data = [arr firstObject];
        [new setTitle:[data objectForKey:@"title"] forState:UIControlStateNormal];
        [clsOtherFun setNewTitle:[data objectForKey:@"title"]];
        new.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    }else if(type == Ants_MyExpressQuery){
        NSDictionary *dic = [pDictionary objectForKey:@"data"];
        if (!ants) {
            ants = [[clsAntsService alloc]init];
            ants.delegate=self;
        }
        [ants GetUserMoney:[clsOtherFun getencodeName]];
        if ([[dic objectForKey:@"data"]isKindOfClass:[NSDictionary class]]) {
            NSDictionary *data =[dic objectForKey:@"data"];
            NSArray *rows = [data objectForKey:@"rows"];
            _tableList = [clsCategory GetDataByArr:rows];
        }else{
        }
        [self loadDataSource];
    }else if (type == Ants_GetUserMoney){
         NSDictionary *dic = [pDictionary objectForKey:@"data"];
        NSString *status = [dic objectForKey:@"status"];
        if ([status integerValue]==200) {
            NSString *data = [dic objectForKey:@"data"];
            [clsOtherFun setVIPMoney:[NSString stringWithFormat:@"%.2f",[data floatValue]]];
            membermoney.text = [NSString stringWithFormat:@"M幣：%.2f",[[clsOtherFun getVIPMoney]floatValue]];
        }
        [ants GetHotNews];
    }
    
}

- (void)NewAction:(UIButton *)sender
{
    NewsController *news = [[NewsController alloc]initWithNibName:@"NewsController" bundle:nil];
    news.isBack=YES;
    [self.navigationController pushViewController:news animated:YES];
}
-(void)logout:(UIButton *)sender
{
    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"取消" action:^{
        
    }];
    RIButtonItem *sure = [RIButtonItem itemWithLabel:@"確定" action:^{
        [clsOtherFun setUser:nil];
        [clsOtherFun setencodeName:@""];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginChange" object:nil];
    }];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"是否登出？" cancelButtonItem:cancel otherButtonItems:sure, nil];
    [alert show];
}
-(void)login:(UIButton *)sender
{
    LoginViewController *login = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
    login.isBack=YES;
    [self.navigationController pushViewController:login animated:YES];
}
-(UILabel *)CreatByText:(NSString *)text :(NSUInteger)tag
{
    UILabel *status = [[UILabel alloc]initWithFrame:CGRectZero];
    status.text=text;
    status.tag=tag;
    status.textAlignment= NSTextAlignmentCenter;
    status.translatesAutoresizingMaskIntoConstraints = NO;
    status.font = [UIFont systemFontOfSize:15];
    status.textColor=[UIColor blackColor];
    return status;
}
-(void)getHotNew
{
    if ([clsOtherFun CheckNetworkStatus:YES]) {
        [clsOtherFun showLoadingView:@"正在獲取數據"];
        if (!ants) {
            ants = [[clsAntsService alloc]init];
            ants.delegate=self;
        }
        [ants GetHotNews];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 8;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"MainViewCell";
    MainViewCell * cell = [self.collection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    NSUInteger item =indexPath.row;
    clsMain *collet = [_list objectAtIndex:item];
    [cell fillViewWithObject:collet];
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==2|indexPath.row==6) {
        return CGSizeMake(Cell1Width, Cell1Width*85/94-0.5);
    }
    else{
        return CGSizeMake(Cell1Width, Cell1Width*85/94-0.5);
    }
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0,0);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        CalculationController *Calcula = [[CalculationController alloc]initWithNibName:@"CalculationController" bundle:nil];
        Calcula.isBack=YES;
        [self.navigationController pushViewController:Calcula animated:YES];
    }else if (indexPath.row==1) {
        DifficultController *Difficult = [[DifficultController alloc]init];
        [self.navigationController pushViewController:Difficult animated:YES];
    }else if (indexPath.row==2) {
        //代寄服务点击处理
        if (![[clsOtherFun getMemberName]isEqualToString:@""]) {
            RecordsViewController *Records = [[RecordsViewController alloc]initWithNibName:@"RecordsViewController" bundle:nil];
            Records.isBack = YES;
            [self.navigationController pushViewController:Records animated:YES];
//        SendViewController *send = [[SendViewController alloc]init];
//        [self.navigationController pushViewController:send animated:YES];
        }else{
            [self login:nil];
        }
    }else if (indexPath.row==3) {
        if ([[clsOtherFun getMemberName]isEqualToString:@""]) {
            [self login:nil];
        }else{
            WebViewController *webview = [[WebViewController alloc]init];
            webview.urlStr = [@"http://www.ot-express-macau.com:8018/WebApp/Index?code=app"stringByAppendingString:[clsOtherFun getencodeName]];
            [self.navigationController pushViewController:webview animated:true];
        }
        
    }else if (indexPath.row==4) {
        Charge1ViewController *charge = [[Charge1ViewController alloc]initWithNibName:@"Charge1ViewController" bundle:nil];
        charge.isBack=YES;
        [self.navigationController pushViewController:charge animated:YES];
    }else if (indexPath.row==5) {
        WechatViewController *wechat = [[WechatViewController alloc]initWithNibName:@"WechatViewController" bundle:nil];
        wechat.isBack=YES;
        [self.navigationController pushViewController:wechat animated:YES];
    }else if (indexPath.row==6) {
        ProblemViewController *problem = [[ProblemViewController alloc]initWithNibName:@"ProblemViewController" bundle:nil];
        problem.isBack=YES;
        [self.navigationController pushViewController:problem animated:YES];
    }else if (indexPath.row==7) {
        if (![[clsOtherFun getMemberName]isEqualToString:@""]) {
            AccountViewController *accout = [[AccountViewController alloc]initWithNibName:@"AccountViewController" bundle:nil];
            accout.isBack=YES;
            [self.navigationController pushViewController:accout animated:YES];
        }else{
            [self login:nil];
        }
    }
}
- (void)showAD {
    AppDelegate * delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    _modal = [[RNBlurModalView alloc] initWithViewController:delegate.window.rootViewController view:nil];
    [_modal show];
}

- (void)knowAction {
    
    [_modal hide];
}
#pragma mark - Nested Tables methods
- (NSInteger)mainTable:(UITableView *)mainTable numberOfItemsInSection:(NSInteger)section {
    return [_tableList count];
}

- (NSInteger)mainTable:(UITableView *)mainTable numberOfSubItemsforItem:(SDGroupCell *)item atIndexPath:(NSIndexPath *)indexPath {
    return 1;
}

- (SDGroupCell *)mainTable:(UITableView *)mainTable setItem:(SDGroupCell *)item forRowAtIndexPath:(NSIndexPath *)indexPath {
    clsCategory *category = [_tableList objectAtIndex:indexPath.row];
    [item FillDataWithCate:category];
    return item;
}

- (SDSubCell *)item:(SDGroupCell *)item setSubItem:(SDSubCell *)subItem forRowAtIndexPath:(NSIndexPath *)indexPath {
    clsCategory *category = [_tableList objectAtIndex:item.cellIndex];
    [subItem setSubDataWithCate:category];
    return subItem;
}

- (void) mainTable:(UITableView *)mainTable itemDidChange:(SDGroupCell *)item {
}

- (void) mainItem:(SDGroupCell *)item subItemDidChange: (SDSubCell *)subItem forTap:(BOOL)tapped {
    
}
#pragma mark PullTableView2 Delegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    [self getUserData];
}

- (void)pullTableViewDidTriggerLoadMore:(PullTableView*)pullTableView{
    [self getUserData];
}

@end
